import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import axios from 'axios'

function copy(state: any) {
  return JSON.parse(JSON.stringify(state))
}

// 对State数据类型进行检测
export interface HomeModelState {
  name: string
  count: number
}

// 对配置项进行检测
export interface HomeModelType {
  namespace: 'home';
  state: HomeModelState;
  effects: {
    init: Effect;
  };
  reducers: {
    add: Reducer<HomeModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<HomeModelState>;
  };
  //   subscriptions: { setup: Subscription };
}

const HomeModel: HomeModelType = {
  namespace: 'home',
  state: {
    name: 'home中的数据',
    count: 100
  },
  reducers: {
    add(state, action) {
      let NewState = copy(state)
      NewState.count += 1
      return NewState
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },

  effects: {
    *init({ payload }, { call, put }) {
      const data = yield axios.get('https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata')
      console.log(data)
    },
  },

  //   subscriptions: {
  //     setup({ dispatch, history }) {
  //       return history.listen((props: any) => {
  //         if (props.pathname === '/') {
  //           dispatch({
  //             type: 'query',
  //           });
  //         }
  //       });
  //     },
  //   },
};

export default HomeModel;